// Copyright (c) 2023 坚果派
// 公众号：nutpi
// 电话：17752170152
// 官网：https://www.nutpi.net/
// All rights reserved.

import 'dart:convert';
import 'package:http/http.dart' as http;
import '../models/health_news.dart';
import '../models/health_tip.dart';
import '../models/health_reminder.dart';
import '../models/nutrition.dart';
import 'dart:async';
import '../config/keys.dart';
import 'log_service.dart';

class ApiResponse<T> {
  final bool success;
  final String message;
  final T? data;
  final int statusCode;

  ApiResponse({
    required this.success,
    required this.message,
    this.data,
    required this.statusCode,
  });
}

class ApiService {
  static String get apiKey => AppKeys.tianxingApiKey;
  static const String baseUrl = 'https://apis.tianapi.com';
  final LogService _logger = LogService();

  Future<T> _safeApiCall<T>(Future<T> Function() apiCall) async {
    try {
      return await apiCall();
    } on http.ClientException catch (e) {
      throw Exception('网络连接错误: ${e.message}');
    } on FormatException catch (e) {
      throw Exception('数据格式错误: ${e.message}');
    } on TimeoutException catch (e) {
      throw Exception('请求超时: ${e.message}');
    } catch (e) {
      throw Exception('请求失败: $e');
    }
  }

  // 健康资讯
  Future<HealthNewsResponse> getHealthNews({
    int page = 1,
    int pageSize = 10,
    String? keyword,
    bool isRandom = false,
  }) async {
    final String wordParam = keyword != null && keyword.isNotEmpty
        ? '&word=${Uri.encodeComponent(keyword)}'
        : '';

    final Uri uri = Uri.parse(
        '$baseUrl/health/index?key=${apiKey}&num=$pageSize&page=$page$wordParam${isRandom ? '&rand=1' : ''}');

    _logger.debug('Health News Request URL: $uri');

    return _safeApiCall(() async {
      final response = await http.get(uri).timeout(const Duration(seconds: 15));

      if (response.statusCode == 200) {
        final data = json.decode(response.body);
        _logger.debug('Health News API Response: ${response.body}');

        if (data['code'] == 200 && data['result'] != null) {
          if (data['result']['newslist']?.isEmpty ?? true) {
            throw Exception('没有找到相关资讯 (错误码: 250)');
          }
          return HealthNewsResponse.fromJson(data);
        } else {
          throw Exception('API错误: ${data['msg']} (错误码: ${data['code']})');
        }
      } else {
        throw Exception('HTTP错误: ${response.statusCode}');
      }
    });
  }

  // 健康小妙招
  Future<HealthTipResponse> getHealthTips(String symptom) async {
    if (symptom.isEmpty) {
      throw Exception('症状不能为空');
    }

    final Uri uri = Uri.parse(
        '$baseUrl/healthskill/index?key=${apiKey}&word=${Uri.encodeComponent(symptom)}');

    final response = await http.get(uri);

    if (response.statusCode == 200) {
      final data = json.decode(response.body);

      if (data['code'] == 200 && data['result'] != null) {
        return HealthTipResponse.fromJson(data);
      } else {
        throw Exception('API Error: ${data['msg']} (Code: ${data['code']})');
      }
    } else {
      throw Exception('HTTP Error: ${response.statusCode}');
    }
  }

  // 健康提示
  Future<HealthReminder> getHealthReminder() async {
    final Uri uri = Uri.parse('$baseUrl/healthtip/index?key=${apiKey}');

    final response = await http.get(uri);

    if (response.statusCode == 200) {
      final data = json.decode(response.body);

      if (data['code'] == 200 && data['result'] != null) {
        return HealthReminder.fromJson(data);
      } else {
        throw Exception('API Error: ${data['msg']} (Code: ${data['code']})');
      }
    } else {
      throw Exception('HTTP Error: ${response.statusCode}');
    }
  }

  // 营养成分
  Future<NutritionResponse> getNutritionData(String food, int mode) async {
    if (food.isEmpty) {
      throw Exception('食品名称不能为空');
    }

    final Uri uri = Uri.parse(
        '$baseUrl/nutrient/index?key=${apiKey}&word=${Uri.encodeComponent(food)}&mode=$mode');

    _logger.debug('Nutrition Request URL: $uri');

    final response = await http.get(uri);

    if (response.statusCode == 200) {
      final data = json.decode(response.body);
      _logger.debug('Nutrition API Response: ${response.body}');

      if (data['code'] == 200 && data['result'] != null) {
        return NutritionResponse.fromJson(data);
      } else {
        throw Exception('API Error: ${data['msg']} (Code: ${data['code']})');
      }
    } else {
      throw Exception('HTTP Error: ${response.statusCode}');
    }
  }
}
